<?php
//db connect
require 'connect_pdo.php';
require 'classes.php';
//other includes
include 'functions.php';
include 'api.php';

//try to show as a formatted email
include 'mailheader.php';

$pdo = new pdo_query;

//get all characters into array
$pdo->try_query("SELECT char_id, upper(name), upper(realm) FROM char_summary");
$sqlGetChars = $pdo->result;

//for each character in the char_summary table....
foreach ($sqlGetChars as $row)
{
	//reset character variables for each character
	$char_id = $row[0];
	$char = stripslashes(stripslashes($row[1]));
	$realm = stripslashes(stripslashes($row[2]));

	//NOTE - THIS IS USED TO DEFINE ALL VARIABLES USED IN THE UPDATE
	//ALL VARIABLES MUST BE ADDED HERE
	
	//begin row for character
	echo "<table>";
	try
	{
		$character = $api->getCharacterApi()->getCharacter($realm, $char, 
		array('guild', 'stats', 'items', 'titles', 'professions', 'talents', 'reputation', 'achievements'));
		include 'updatevars.php';
		include 'updateqrs.php';
				
		
		//BEGIN UPDATE
		//If last login date in variable is after last login date in table, run update
		if (strtotime($lastLogin) > strtotime($sqlCharHistResult[4]))
		{
			echo "<tr><td>$char ($char_id) - $realm updated-start</td><br/><br/>";

			//update character summary with race, class etc.
			//we should really do a new record if the faction is different and somehow link the two

			//summary also holds all achievements completed with datetimes
			//build achievements completed array
			//clear arrays
			unset($comp_ar);
			unset($compTime_ar);
			$comp_ar=array();
			$compTime_ar=array();
			foreach ($characterAchievements['achievementsCompleted'] as $comp)
			{
				$comp_ar[]=$comp;
			}
			//build timestamps array
			foreach ($characterAchievements['achievementsCompletedTimestamp'] as $compTime)
			{
				$compTime_ar[]=$compTime;
			}
			//combine the arrays
			$achievementTimes = array_combine($comp_ar,$compTime_ar);
			//make the array into an insertable string using custom function
			$achievementDump = array_implode("=>",",",$achievementTimes);

			//get old values and compare
			$pdo->bound_query($sqlSelectCharSum,array($char_id),'All','selectcharsum');
			$charRow = $pdo->result;
			
			//update the character summary
			$pdo->bound_query($sqlUpdateCharSum,array($race,$class,$faction,$achievementDump,$image,$char_id),'None','updatecharsum');

			//create character history record
			$pdo->bound_query($sqlInsertCharHistory,array($char_id, $lastLogin, $points, $guildName, $level, $itemLevel, $talent1, 				$talent2),'None','insert history');	
			
			//get character history id for more detailed records
			$charHistoryId = $pdo->rownum;
			echo "Char history id is $charHistoryId";

			//allow the variable to be used by recalling the query file
			include 'updateqrs.php';

			if (empty($charHistoryId))
				{echo "<td>Character history record could not be inserted</td>";}
			else
			{
				//execute both queries
				$pdo->bound_query($sqlInsertCharStats,array($charHistoryId,$health,$mana,$strength,$agility,$stamina,$intellect,				$spirit,$armor, $power,  $critchance_percent),'None');
				$charstatsrow = $pdo->rownum;
				
				if (empty($charstatsrow))
					{
					echo "<td>Character stats record could not be inserted</td>";			
					}
				else
					{echo "<td>Character stats record inserted</td>";}
				
				$pdo->bound_query($sqlInsertCharItems, array($charHistoryId,$main_dps,$off_dps,$hitRating),'None');
				$charitemstatsrow = $pdo->rownum;
				
				if (empty($charitemstatsrow))
					{echo "<td>Character item stats record could not be inserted</td>";}
				else
					{echo "<td>Character item stats record inserted</td>";}


				//insert item records
				if (!include 'updateitems.php')
				{echo "<td>File not found</td>";}
				else
				{echo "<td>Updating items</td><br/>";}

				//is the code actually being executed correctly when we do this?

				//insert reputation records
				if (!include 'updatereps.php')
				{echo "<td>File not found</td>";}
				else
				{echo "<td>Updating reps</td><br/>";}

				//create profession records
				$i=0;
				while ($i <=2)
				{
				//clear the array to prevent it being reinserted
				unset ($profRecipe_ar);
				$profRecipe_ar = array();
					if (($prof[$i]<>'')&&($prof[$i]<>'None'))
					{
						if (in_array($characterProfs[$i]['id'],$recipeProfs))
						{
							//add recipes to array
							foreach ($characterProfs[$i]['recipes'] as $recipe)
							{
								$profRecipe_ar[] = $recipe;
							}
							//make the array writeable
							$profDump = array_implode("=>",",",$profRecipe_ar);
						}
						else 
						{$profDump = '';}


						$sqlInsertProfs = "INSERT into char_history_pro (char_history_id, pro_name, pro_val, pro_max, recipes, type, 						datestamp, userstamp) VALUES (?,?,?,?,?, 'P',(select now()),1)";
					
						$pdo->bound_query($sqlInsertProfs,array($charHistoryId,$prof[$i],$profval[$i],$profmax[$i],									$profDump),'None');
						$insertprofs = $pdo->rownum;
						
						if (empty($insertprofs))
							{echo "<td>Character professions record could not be inserted</td>";}
						else 
							{echo "<td>Character professions updated</td>";}
					}
					$i++;
				}//end primary profs
				//create secondary skill records
				$i=0;
				while ($i <=4)
				{
				//clear the array to prevent it being reinserted
				unset ($skillRecipe_ar);
				$skillRecipe_ar = array();
					if (($skill[$i]<>'')&&($skill[$i]<>'None'))
					{
						
						if (in_array($characterSkills[$i]['id'],$recipeProfs))
						{
							//add recipes to array
							foreach ($characterSkills[$i]['recipes'] as $recipe)
							{
								$skillRecipe_ar[] = $recipe;
							}
							//make the array writeable
							$skillDump = array_implode("=>",",",$skillRecipe_ar);

						}
						else 
						{$skillDump = '';}

						$sqlInsertProfs = "INSERT into char_history_pro (char_history_id, pro_name, pro_val, pro_max, recipes, type, 						datestamp, userstamp) VALUES (?,?,?,?,?, 'S', (select now()),1)";
			
						$pdo->bound_query($sqlInsertProfs,array($charHistoryId,$skill[$i],$skillval[$i],$skillmax[$i],$skillDump),'None');
						$insert2profs = $pdo->rownum;
						
						if (empty($insert2profs))
							{echo "<td>Character secondary professions record could not be inserted </td>";}
						else
							{echo "<td>Character secondary professions updated</td>";}
					}
					$i++;
				}//end secondary profs
				$i=0;


			}//end history update
			echo "<td>" . $char . " . " . $realm . " updated-end" . "<br/><br/></td></tr>";

		}//end update
		else
		{
			echo "<td>$char  $realm not updated<br/><br/></td></tr>";

		}

		//end try

	}
	catch (exception $e)
	{
		echo 'Caught exception: ', $e->getMessage();
		echo $char . " . " . $realm . " inactive" . "<br/><br/>";
		$sqlSetInactive = "UPDATE char_summary SET active=0 WHERE char_id = ?";
		$pdo->bound_query($sqlSetInactive,array($char_id),'None');

		//exit;
	}

	//end row for character
	echo "</table>";



}//end update

include 'mailfooter.php';

?>